/** 2. 全局数据表格生成脚本 */
<template>
  <div class="editor_container">
    <div class="code-container">
      <div class="script-header">
        <a-button
          type="primary"
          :loading="updateLoading"
          @click="onUpdateScript"
          >更新脚本</a-button
        >
      </div>
      <MonacoEditor
        editorId="siteCategoryEditor"
        v-model="script_code"
        lang="python"
      />
    </div>
    <div class="result-container">
      <div class="result-header">
        <h4>源数据 JSON</h4>
        <div class="result-header-end">
          <a-button :disabled="!excel_href" @click="download_result">
            下载结果
          </a-button>
          <a-button type="primary" @click="execute">
            <RocketOutlined />
            执行生成
          </a-button>
        </div>
      </div>
      <div class="script-body">
        <MonacoEditor
          editorId="dataGridResultEditor"
          v-model="result_code"
          @change="result_update"
          ref="dataGridResultEditor"
          lang="json"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import MonacoEditor from "@/components/commons/MonacoEditor.vue";
import { ref, onMounted, defineExpose } from "vue";
import {
  get_global_config_by_key,
  update_global_config_by_key,
} from "@/utils/storage.js";
import { excel_generate } from "@/utils/selection.js";

import { message } from "ant-design-vue";

const script_id = ref(-1);
const script_code = ref('print("Hello World!")');
const result_code = ref("[]");
const script_params_json = ref("");
const updateLoading = ref(false);
const excel_href = ref("");

const download_result = () => {
  const a = document.createElement("a");
  a.href = excel_href.value;
  a.download = `output-${new Date().getTime()}.xlsx`;
  a.click();
};

// 执行脚本
const execute = async () => {
  try {
    const res = await excel_generate(JSON.parse(result_code.value));
    console.log("res ->", res);
    excel_href.value = JSON.parse(res.data);
    if (excel_href.value) {
      message.success("执行脚本完成");
    } else {
      message.error("执行脚本失败: 返回结果为空");
    }
  } catch (err) {
    message.error("执行脚本时发生错误");
    console.error("execute script error ->", err);
  }
};

const reload = async () => {
  // 设置暂存运行结果
  let category_result = localStorage.getItem(`global-dataGridResult`);
  if (category_result && this.$refs.dataGridResultEditor) {
    this.$refs.dataGridResultEditor.setEditorValue(category_result);
  }
  // 获取全局页面数据
  let script = await get_global_config_by_key("GLOBAL_EXCEL_GENERATE");
  if (script) {
    script_code.value = script.configValue;
    script_id.value = script.extraInfo;
  } else {
    message.error("获取全局类目脚本失败");
  }
};
const onUpdateScript = async () => {
  updateLoading.value = true;
  await update_global_config_by_key(
    "GLOBAL_EXCEL_GENERATE",
    script_code.value,
    script_id.value,
    script_params_json.value
  );
  updateLoading.value = false;
};

const result_update = (value) => {
  console.log("value ->", value);
  result_code.value = value;
};

onMounted(() => {
  reload();
});

defineExpose({
  reload,
});
</script>

<script>
import { Button } from "ant-design-vue";
import { RocketOutlined } from "@ant-design/icons-vue";

export default {
  name: "SetCategoryScript",
  components: {
    MonacoEditor,
    AButton: Button,
    RocketOutlined,
  },
};
</script>

<style lang="scss" scoped>
.editor_container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;

  .code-container {
    height: 100%;
    width: 52%;
    display: flex;
    flex-direction: column;
  }

  .script-header {
    height: 50px;
    display: flex;
    align-items: center;
  }

  .script-body {
    flex: 1;
    width: 100%;
    min-height: 0;
  }

  .result-container {
    width: 46%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .result-header {
      height: 50px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
  }
}
</style>
